package com.platform.hjt.flow.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.snaker.engine.access.QueryFilter;
import org.snaker.engine.entity.HistoryTask;
import org.snaker.engine.entity.Process;
import org.snaker.engine.entity.Task;
import org.snaker.engine.helper.AssertHelper;
import org.snaker.engine.helper.StreamHelper;
import org.snaker.engine.model.ProcessModel;
import org.snaker.engine.model.TaskModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.platform.hjt.base.controller.BaseController;
import com.platform.hjt.base.costant.StateValue;
import com.platform.hjt.flow.service.SnakerEngineFacets;
import com.platform.hjt.flow.tools.SnakerHelper;
import com.platform.hjt.sys.model.SysCompanyInfo;
import com.platform.hjt.sys.service.SysCompanyInfoService;

@Controller
@RequestMapping(value = "/flow/process")
public class ProcessController  extends BaseController{

	@Autowired
	private SnakerEngineFacets facets;
	@Resource
	private SysCompanyInfoService sysCompanyInfoService;
	
	/**
	 * 新建流程定义[web流程设计器]
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/designer.html", method=RequestMethod.GET)
	public String processDesigner(Model model) {
		//每个公司活动的订单流程只有一个
		SysCompanyInfo currCompany = sysCompanyInfoService.getSysCompanyInfo("sysCompanyInfoId", sysCompanyInfoService.getSessionSysCompanyInfo().getSysCompanyInfoId());
		String processId = currCompany.getOrderProcessId();
		
		if(StringUtils.isNotEmpty(processId)) {
			Process process = facets.getEngine().process().getProcessById(processId);
			AssertHelper.notNull(process);
			ProcessModel processModel = process.getModel();
			if(processModel != null) {
				String json = SnakerHelper.getModelJson(processModel);
				model.addAttribute("process", json);
			}
			model.addAttribute("processId", processId);
		}
		return "page/flow/processDesigner";
	}
	
	/**
	 * 保存流程定义[web流程设计器]
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/deployXml.do", method=RequestMethod.POST)
	@ResponseBody
	public boolean processDeploy(String model, String id) {
		InputStream input = null;
		String porcessId;
		try {
			String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + SnakerHelper.convertXml(model);
			input = StreamHelper.getStreamFromString(xml);
			
			/*if(StringUtils.isNotEmpty(id)) {
				//这个不重新发布是因为redeploy是更新process中的content字段，这样做会导致再运行的流程实例，找不到原来的流程而报错。
				//facets.getEngine().process().redeploy(id, input);
				facets.getEngine().process().undeploy(id);
				porcessId = facets.getEngine().process().deploy(input);
			} else {
				porcessId = facets.getEngine().process().deploy(input);
			}*/
			porcessId = facets.deployProcess(id, input);
			facets.getEngine().process().updateType(porcessId, StateValue.OrderProcessType.getKey());
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			if(input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		//每个公司活动的订单流程只有一个
		SysCompanyInfo currCompany = sysCompanyInfoService.getSysCompanyInfo("sysCompanyInfoId", sysCompanyInfoService.getSessionSysCompanyInfo().getSysCompanyInfoId());
		currCompany.setOrderProcessId(porcessId);
		//更新公司流程
		sysCompanyInfoService.saveSysCompanyInfo(currCompany);
		
		return true;
	}
	
	 /**
     * 通用的流程展现页面入口
     * 将流程中的各环节表单以tab+iframe方式展现
     */
    @RequestMapping(value = "/all.html")
    public String all(Model model, String processId, String orderId, String taskId) {
		model.addAttribute("processId", processId);
		model.addAttribute("orderId", orderId);
		model.addAttribute("taskId", taskId);
		
        if(StringUtils.isNotEmpty(processId)) {
            model.addAttribute("process", facets.getEngine().process().getProcessById(processId));
        }
        if(StringUtils.isNotEmpty(orderId)) {
            model.addAttribute("order", facets.getEngine().query().getOrder(orderId));
        }
        if(StringUtils.isNotEmpty(taskId)) {
            model.addAttribute("task", facets.getEngine().query().getTask(taskId));
        } 
        
        if(null != getRequest().getParameter("isView")){
        	model.addAttribute("isView", true	);
        } else{
        	model.addAttribute("isView", false);
        }
        
        return "page/flow/all";
    }
    
	 /**
     * 通用的流程展现页面入口
     * 将流程中的各环节表单以tab+iframe方式展现
     */
    @RequestMapping(value = "/getAll.html")
    public String getAll(HttpServletResponse response, Model model, String processId, String orderId, String taskId) {
    	
		model.addAttribute("processId", processId);
		model.addAttribute("orderId", orderId);
		model.addAttribute("taskId", taskId);
		
        if(StringUtils.isNotEmpty(processId)) {
            model.addAttribute("process", facets.getEngine().process().getProcessById(processId));
        }
        if(StringUtils.isNotEmpty(orderId)) {
            model.addAttribute("order", facets.getEngine().query().getOrder(orderId));
        }
        if(StringUtils.isNotEmpty(taskId)) {
        	Task task = facets.getEngine().query().getTask(taskId);
            model.addAttribute("task", task);
            return "forward:"+task.getActionUrl();
        } 
        
        if(null != getRequest().getParameter("isView")){
        	model.addAttribute("isView", true	);
        } else{
        	model.addAttribute("isView", false);
        }
        
        return "page/flow/all";
    }
    
   
    
    /**
     * 节点信息以json格式返回
     * all页面以节点信息构造tab及加载iframe
     */
    @RequestMapping(value = "/node.do")
    @ResponseBody
    public Object node(String processId) {
        Process process = facets.getEngine().process().getProcessById(processId);
        List<TaskModel> models = process.getModel().getModels(TaskModel.class);
        List<TaskModel> viewModels = new ArrayList<TaskModel>();
        for(TaskModel model : models) {
            TaskModel viewModel = new TaskModel();
            viewModel.setName(model.getName());
            viewModel.setDisplayName(model.getDisplayName());
            viewModel.setForm(model.getForm());
            viewModels.add(viewModel);
        }
        return viewModels;
    }
    
    /**
     * 显示独立的流程图
     */
    @RequestMapping(value = "diagram.html", method=RequestMethod.GET)
    public String diagram(Model model, String processId, String orderId) {
        model.addAttribute("processId", processId);
        model.addAttribute("orderId", orderId);
        return "page/flow/diagram";
    }
    
    /**
     * 获取流程图的节点信息
     * @Description 
     * @author huangjt
     * @param processId
     * @param orderId
     * @return
     */
	@RequestMapping(value = "/json.do", method=RequestMethod.GET)
	@ResponseBody
	public Object json(String processId, String orderId) {
        Process process = facets.getEngine().process().getProcessById(processId);
        AssertHelper.notNull(process);
        ProcessModel model = process.getModel();
        Map<String, String> jsonMap = new HashMap<String, String>();
        if(model != null) {
            jsonMap.put("process", SnakerHelper.getModelJson(model));
        }

		if(StringUtils.isNotEmpty(orderId)) {
			List<Task> tasks = facets.getEngine().query().getActiveTasks(new QueryFilter().setOrderId(orderId));
			List<HistoryTask> historyTasks = facets.getEngine().query().getHistoryTasks(new QueryFilter().setOrderId(orderId));
			jsonMap.put("state", SnakerHelper.getStateJson(model, tasks, historyTasks));
		}
        //{"historyRects":{"rects":[{"paths":["TO 任务1"],"name":"开始"},{"paths":["TO 分支"],"name":"任务1"},{"paths":["TO 任务3","TO 任务4","TO 任务2"],"name":"分支"}]}}
		return jsonMap;
	}
	
	@RequestMapping(value = "/tip.do", method=RequestMethod.GET)
    @ResponseBody
    public Map<String, String> addTaskActor(String orderId, String taskName) {
        List<Task> tasks = facets.getEngine().query().getActiveTasks(new QueryFilter().setOrderId(orderId));
        StringBuilder builder = new StringBuilder();
        String createTime = "";
        for(Task task : tasks) {
            if(task.getTaskName().equalsIgnoreCase(taskName)) {
            	
                //String[] actors = facets.getEngine().query().getTaskActorsByTaskId(task.getId());
            	String[] actors = facets.getSnakerMyQuery().getTaskActorsNameByTaskId(task.getId());
            	
                for(String actor : actors) {
                    builder.append(actor).append(",");
                }
                createTime = task.getCreateTime();
            }
        }
        if(builder.length() > 0) {
            builder.deleteCharAt(builder.length() - 1);
        }
        Map<String, String> data = new HashMap<String, String>();
        data.put("actors", builder.toString());
        data.put("createTime", createTime);
        return data;
    }
	
}
